package cn.basic.auth.interceptor;

import cn.basic.auth.annotation.BasicPermission;
import cn.basic.auth.mapper.PermissionMapper;
import cn.basic.common.domain.BusinessLog;
import cn.basic.common.mapper.BusinessMapper;
import cn.basic.org.domain.Employee;
import cn.basic.org.dto.DepartmentDTO;
import cn.basic.org.vo.result.DepartmentVo;
import cn.basic.utils.BasicMap;
import cn.basic.utils.BodyRequestWrapper;
import cn.basic.utils.SnowFlakeUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.databind.util.JSONWrappedObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spring.web.readers.parameter.ParameterRequiredReader;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * description:
 * 认证拦截 // 权限拦截
 * <br>
 * date: 2023/3/7 14:48 <br>
 * author: ZhaoLc <br>
 * version: 1.0 <br>
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${enable-sql-log}")
    private boolean enableSqlLog;

    @Resource
    PermissionMapper permissionMapper;

    @Resource
    BusinessMapper businessMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 认证拦截--登陆
        // 获取前端请求头的token
        String token = request.getHeader("token");
        // 判断token是否为空，为空未登录 返回错误信息
        if(StringUtils.isEmpty(token)){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }

        // 未登录，拦截
        Object loginUser = BasicMap.loginMap.get(token);
        if(Objects.isNull(loginUser)){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }
        Employee employee = (Employee) loginUser;

        // 添加日志
        String operationType = request.getHeader("operation_type");
        String businessId = request.getHeader("business_id");
        if(!StringUtils.isEmpty(operationType)&&!StringUtils.isEmpty(businessId)&&enableSqlLog){
            Long snowFlakeId = SnowFlakeUtil.getSnowFlakeId();
            Date startTime = new Date();
            BusinessLog businessLog = new BusinessLog();
            // 进行中
            businessLog.setStatus(0L);
            // 操作人
            businessLog.setOperationId(employee.getId());
            // 业务编号
            businessLog.setBusinessId(businessId);
            // 开始时间
            businessLog.setStartTime(startTime);
            // 操作类型
            businessLog.setOperationType(operationType);
            businessLog.setBatchId(snowFlakeId);
            businessMapper.add(businessLog);
            request.setAttribute("batchId",snowFlakeId);
        }
//
//        // 判断是否需要权限，不需要权限直接放行 方法权限判断
//        if(handler instanceof HandlerMethod){
//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            Method method = handlerMethod.getMethod();
//            BasicPermission annotation = method.getAnnotation(BasicPermission.class);
//            if(Objects.isNull(annotation)){
//                return true;
//            }
//            List<String> permissionSns = permissionMapper.getPermissionSnsByEmployeeId(employee.getId());
//
//            // 获取 类名:方法名
//            String sn = method.getDeclaringClass().getSimpleName()+":"+method.getName();
//
//            if(!permissionSns.contains(sn)){
//                response.getWriter().write("{\"success\":false,\"message\":\"noAuth\"}");
//                return false;
//            }
//        }

        // 如果需要权限 进行比对
        return true;
      /*  return HandlerInterceptor.super.preHandle(request, response, handler);*/
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Date endTime = new Date();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
